# -*- coding:utf-8 *-
# 项目       :    练习题 
# 文件       :    Sum_collect_xin.py
# 作者       :    zhangchen 
# 时间       :    2021/4/21  8:46 上午 
# IDE       :    PyCharm

from application import db, Config
from sqlalchemy import create_engine

from application.apps.collect.service.Collects import summary
from application.libs import const
from application.models.models import CollectSum


class sums:
    host_global = Config.SUMS_HOST  # 根据开发生产环境切换92/98
    port_global = Config.SUMS_PORT
    user_global = Config.SUMS_USER
    passwd_global = Config.SUMS_PASSWD
    db_global = Config.SUMS_DB

    def __init__(self, sql="SELECT * FROM collect where pstatus != 1 and `status` !=0"):
        """
        :param sql: sql
        """
        host = self.host_global
        port = self.port_global
        user = self.user_global
        passwd = self.passwd_global
        db = self.db_global
        import pandas as pd
        engine = create_engine(f'mysql+pymysql://{user}:{passwd}@{host}:{port}/{db}', echo=False)
        pd.options.display.max_rows = None
        self.data = pd.read_sql(sql, engine)

    def group(self):
        '''
        查询所有业务线名称
        :return:
        '''
        group_list = []
        for i in self.data.group.unique():
            group_list.append(i)
        return group_list

    def status(self):
        # 更改新数据的状态码
        db.session.query(CollectSum).filter(CollectSum.status == 1).update({"status": 0})
        try:
            db.session.commit()
            msg = const.OPERATE_SUCCESS
        except:
            # 事務回滾
            db.session.rollback()
            msg = const.OPERATE_FAIL

    def starsql(self, data_dict):
        # 数据进行插入
        host = self.host_global
        port = self.port_global
        user = self.user_global
        passwd = self.passwd_global
        db = self.db_global
        try:
            engine = create_engine(f'mysql+pymysql://{user}:{passwd}@{host}:{port}/{db}', echo=False)
            data_dict.to_sql('collect_sum', if_exists='append', con=engine, index=False)
            msg = const.OPERATE_SUCCESS
        except:
            # 事務回滾
            # db.session.rollback()
            msg = const.OPERATE_FAIL
        return msg


def mainFun(nature_week=1):
    """
    *定时任务调用的和方法是这个类似，但是还是不一致的部分，此方法有修改时，注意不能直接拿此脚本相关的文件直接替换定时任务的文件，单独修改定时任务的脚本
    手动生成本周周报入口
    :param nature_week:1表示非自然周
    :return:string
    """
    import pandas as pd
    run = sums()
    suma = summary()
    l = []
    group_list = run.group()
    whole_project_nums = len(group_list)
    whole_bug_rate = 0
    whole_Invalid_rate = 0
    whole_release_rate = 0
    for i in group_list:
        d = {'business': i, 'project_nums': suma.sum_project_nums(run.data[run.data['group'] == i]),
             'count_times': suma.sum_count_times(run.data[run.data['group'] == i]),
             'status': 1,
             'access_rate': suma.sum_access_rate(run.data[run.data['group'] == i]),
             'must_rate': suma.sum_must_rate(run.data[run.data['group'] == i]),
             'access_on_rate': suma.sum_access_on_rate(run.data[run.data['group'] == i]),
             'must_out_rate': suma.sum_must_out_rate(run.data[run.data['group'] == i]),
             'release_success': suma.sum_release_success(run.data[run.data['group'] == i]),
             'repair_rate': suma.sum_repair_rate(run.data[run.data['group'] == i]),
             'bug_rate': suma.sum_bug_rate(run.data[run.data['group'] == i]),
             'Invalid_rate': suma.sum_invalid_rate(run.data[run.data['group'] == i]),
             'release_rate': suma.sum_release_rate(run.data[run.data['group'] == i]),
             'change': suma.sum_change(run.data[run.data['group'] == i]),
             'updated_time': suma.updated_time(),
             'type_standard': suma.sum_project_type_标准需求(run.data[run.data['group'] == i]),
             'type_check': suma.sum_project_type_验收需求(run.data[run.data['group'] == i]),
             'type_production_accident': suma.sum_project_type_生产事故(run.data[run.data['group'] == i]),
             'type_online_bug': suma.sum_project_type_线上bug(run.data[run.data['group'] == i]),
             'type_emergency_edition': suma.sum_project_type_紧急发版(run.data[run.data['group'] == i]),
             'nature_week': nature_week,  # 1 表示自然周
             'inflow_demand': suma.sum_inflow_demand(run.data[run.data['group'] == i]),
             'online_demand': suma.sum_online_demand(run.data[run.data['group'] == i]),
             'complete_demand': suma.sum_complete_demand(run.data[run.data['group'] == i]),
             }
        whole_bug_rate += float(d["bug_rate"])
        whole_Invalid_rate += float(d["Invalid_rate"])
        whole_release_rate += float(d["release_rate"])
        l.append(d)
        for j in l:
            # 由于整体的相关数据是累计相加计算的，所以遍历集合：l，给每周的数据都添加上整体计算的值，比如本周各业务线的整体bug率是0.3，
            # 那么本周的每个业务线的整体bug率字段都为0.3
            j["whole_bug_rate"] = suma.cal_whole_project_nums(whole_project_nums, whole_bug_rate)
            j["whole_Invalid_rate"] = suma.cal_whole_project_nums(whole_project_nums, whole_Invalid_rate)
            j["whole_release_rate"] = suma.cal_whole_project_nums(whole_project_nums, whole_release_rate)
    msg_s = run.status()  # 修改数据状态-只在手动生成周报的时候回执行此方法
    if msg_s == const.OPERATE_FAIL:
        return const.OPERATE_FAIL
    Data_Frame = pd.DataFrame(l)
    msg = run.starsql(Data_Frame)
    return msg  # 为了在手动生成周报时，可以知道此脚本是否已经正常运行


def collect_sum_real_time(s_date,e_date):
    """
    质量数据-质量数据总览：/collect/collect_sum接口，调用此脚本，查collect表生成最新总览数据
    :return: list
    """
    if s_date != '' and e_date != '':
        sql = f"SELECT * FROM collect where pstatus != 1 and `status` !=0 and (begindate >= '{s_date}' or onlinedate >= '{s_date}' or enddate >= '{s_date}') and (begindate <= '{e_date}' or onlinedate <= '{e_date}' or enddate <= '{e_date}')"
        run = sums(sql)
    else:
        run = sums()

    suma = summary()
    l = []
    group_list = run.group()
    for i in group_list:
        d = {'business': i, 'project_nums': suma.sum_project_nums(run.data[run.data['group'] == i]),
             'count_times': suma.sum_count_times(run.data[run.data['group'] == i]),
             'access_rate': suma.sum_access_rate(run.data[run.data['group'] == i]),
             'must_rate': suma.sum_must_rate(run.data[run.data['group'] == i]),
             'access_on_rate': suma.sum_access_on_rate(run.data[run.data['group'] == i]),
             'must_out_rate': suma.sum_must_out_rate(run.data[run.data['group'] == i]),
             'release_success': suma.sum_release_success(run.data[run.data['group'] == i]),
             'repair_rate': suma.sum_repair_rate(run.data[run.data['group'] == i]),
             'bug_rate': suma.sum_bug_rate(run.data[run.data['group'] == i]),
             'Invalid_rate': suma.sum_invalid_rate(run.data[run.data['group'] == i]),
             'release_rate': suma.sum_release_rate(run.data[run.data['group'] == i]),
             'change': suma.sum_change(run.data[run.data['group'] == i])
             }
        l.append(d)
    return l
